//
//  HotViewController.m
//  Comic
//
//  Created by Andy.He on 16/3/10.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "HotViewController.h"
#import "HotTableViewCell.h"
#import "HotBannerCollectionViewCell.h"
#import "HotBannerModel.h"
#import "HotModel.h"
#import "ClassifyModel.h"
#import "ClassifyCollectionViewCell.h"
#import "ComiContentViewController.h"
#import "DetailViewController.h"
//#import "SearchViewController.h"

#define Data @"http://api.kuaikanmanhua.com/v1/banners"
#define Details @"http://api.kuaikanmanhua.com/v1/topic_lists/mixed"
#define ClassifyData @"http://api.kuaikanmanhua.com/v1/tag/suggestion"

@interface HotViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *hotTableView;  // 详情轮播图

@property (strong, nonatomic) IBOutlet UIView *hotView;  // 轮播图下面View

@property (weak, nonatomic) IBOutlet UICollectionView *hotCollectionView; // 轮播图
@property(nonatomic,strong)NSMutableArray *bannerArr;  // 轮播图数组

@property (strong, nonatomic) IBOutlet UISegmentedControl *classify;

@property(nonatomic,strong)NSMutableArray *detailsArr;  // TableView数据

@property(nonatomic,retain)NSTimer *myTimer;  // 时间计时器

@property(nonatomic,strong)UISegmentedControl *category;  // 分类热门

@property (weak, nonatomic) IBOutlet UICollectionView *classifyCollectionView;

@property(nonatomic,strong)NSMutableArray *classifyArr;
@property(nonatomic,assign)NSNumber *type;
@property(nonatomic,copy)NSString *titleID;
@end

@implementation HotViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    // 轮播图数据解析
    [self createData];
    
    // TableView数据解析
    [self tableViewData];
    
    // 分类数据解析
    [self classifyData];
    
    // 创建TableView和collectionView
    [self createView];
    
    // 创建分类collectionView
    [self classifyView];
    
    // 刷新
    self.hotTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(TableViewRefresh)];
    

    // 创建UISegmentedControl
    self.navigationItem.titleView = self.classify;
    
    // 隐藏边框 设置点击字体颜色
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName: [UIColor colorWithRed:0.992 green:0.796 blue:0.258 alpha:1.000]};
    
    [self.classify setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName: [UIColor blackColor]};
    
    [self.classify setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    
    // 设置点击方法
    [self.classify addTarget:self action:@selector(doSomethingInSegment:)forControlEvents:UIControlEventValueChanged];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    searchButton.frame = CGRectMake(0, 0, 20, 20);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:searchButton];
    [searchButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark 刷新
- (void)TableViewRefresh{
    
    // TableView数据解析
    [self tableViewData];
    
    [self createData];
}

#pragma mark 轮播图数据解析
- (void)createData{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:Data parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 初始化数组
        self.bannerArr = [NSMutableArray array];
        
        NSArray *arr = [responseObject[@"data"]objectForKey:@"banner_group"];
        
        for (NSDictionary *dic in arr) {
            
            HotBannerModel *model = [[HotBannerModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.bannerArr addObject:model];
            
            _BannerPage.numberOfPages = _bannerArr.count;
        }
        
        [self.hotCollectionView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    // 判断网络状态
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

#pragma mark TableView数据解析
- (void)tableViewData{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:Details parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.detailsArr = [NSMutableArray array];
        
        NSArray *arr = [responseObject[@"data"]objectForKey:@"topics"];
        
        for (NSDictionary *dic in arr) {
            
            HotModel *model = [[HotModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.detailsArr addObject:model];
            
        }
    
        [self.hotTableView.mj_header endRefreshing];
        
        [self.hotTableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    // 判断网络状态
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

#pragma mark 分类数据解析
- (void)classifyData{
    
    self.classifyArr = [NSMutableArray array];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:ClassifyData parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = [responseObject[@"data"]objectForKey:@"suggestion"];
        
        for (NSDictionary *dic in arr) {
            
            ClassifyModel *model = [[ClassifyModel alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.classifyArr addObject:model];
            
            [self.classifyCollectionView reloadData];
            
        }
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
    }];
    
    // 判断网络状态
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
}

#pragma mark  切换视图点击方法
- (void)doSomethingInSegment:(UISegmentedControl *)segmented{
    
    NSInteger index = segmented.selectedSegmentIndex;
    
    if (index == 1) {
        
        self.hotTableView.hidden = YES;
        
        self.hotView.hidden = YES;
        
        self.classifyCollectionView.hidden = NO;
    }else{
        
        self.hotTableView.hidden = NO;
        
        self.hotView.hidden = NO;
        
        self.classifyCollectionView.hidden = YES;
        
    }
}

#pragma mark 创建分类collectionView
- (void)classifyView{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    // 列间距
    flowLayout.minimumLineSpacing = 10;
    
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH / 3 , 170);
    
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    
    [self.classifyCollectionView setCollectionViewLayout:flowLayout];
    
    // 取消翻页条
    self.classifyCollectionView.showsHorizontalScrollIndicator = NO;
    
    UINib *classifyCellNib = [UINib nibWithNibName:NSStringFromClass([ClassifyCollectionViewCell class]) bundle:nil];
    
    [self.classifyCollectionView registerNib:classifyCellNib forCellWithReuseIdentifier:NSStringFromClass([ClassifyCollectionViewCell class])];
    
    // 刷新
    
}

#pragma mark 创建TableView和collectionView
- (void)createView{
    
    // 定时器
    [self addtimer];
    
    // 注册TableView
    UINib *cellNib = [UINib nibWithNibName:NSStringFromClass([HotTableViewCell class]) bundle:nil];
    
    [self.hotTableView registerNib:cellNib forCellReuseIdentifier:NSStringFromClass([HotTableViewCell class])];
    
    self.hotTableView.backgroundColor = [UIColor whiteColor];
        
    // 添加头视图
    self.hotTableView.tableHeaderView = self.hotView;
    
    // 设置collectionViewFlowLayout
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    // 滚动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    // 列间距
    flowLayout.minimumLineSpacing = 0;
    
    flowLayout.itemSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT / 4 - 10);
    
    [self.hotCollectionView setCollectionViewLayout:flowLayout];
    
    self.hotCollectionView.backgroundColor = [UIColor whiteColor];
    
    // 取消翻页条
    self.hotCollectionView.showsHorizontalScrollIndicator = NO;
    
    // 按页滑动
    self.hotCollectionView.pagingEnabled = YES;
    
    // 注册collectionView
    UINib *collectionNib = [UINib nibWithNibName:NSStringFromClass([HotBannerCollectionViewCell class]) bundle:nil];
    
    [self.hotCollectionView registerNib:collectionNib forCellWithReuseIdentifier:NSStringFromClass([HotBannerCollectionViewCell class])];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(change:) name:@"xiaozaoren" object:nil];
    
}

- (void)change:(NSNotification *)notigication{
    
    NSString *ID = notigication.userInfo[@"1"];
    
    NSString *type = notigication.userInfo[@"2"];
    
    NSLog(@"%@",type);

    
    
    if ([type isEqualToString:@"hot"]) {
        DetailViewController *detaVC = [[DetailViewController alloc] init];
        detaVC.idNumber = [NSString stringWithFormat:@"%@",ID];
        [self.navigationController pushViewController:detaVC animated:YES];
    }else{
        ComiContentViewController *comicVC = [[ComiContentViewController alloc] init];
        comicVC.idNUmber = [NSString stringWithFormat:@"%@",ID];
        [self.navigationController pushViewController:comicVC animated:YES];
    }
    
}

- (void)setPicArr:(NSMutableArray *)picArr{
    
    if (_bannerArr != picArr) {
        
        _bannerArr = picArr;
        
    }
    
    [_hotCollectionView reloadData];
    
    _BannerPage.numberOfPages = _bannerArr.count;
    
}

#pragma mark collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (collectionView == self.hotCollectionView) {
        
        return self.bannerArr.count;
        
    }else{
        
        return self.classifyArr.count;
        
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == _hotCollectionView) {
    
    HotBannerModel *model = self.bannerArr[indexPath.item];
    
    HotBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([HotBannerCollectionViewCell class]) forIndexPath:indexPath];
    
//    [cell.bannerImageView sd_setImageWithURL:[NSURL URLWithString:model.pic]];
    
        [cell.bannerImageView setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
    
    return cell;
        
    }else if (collectionView == _classifyCollectionView){
        
        ClassifyModel *model = self.classifyArr[indexPath.row];
        
        ClassifyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([ClassifyCollectionViewCell class]) forIndexPath:indexPath];
        
        cell.name.text = model.title;
        cell.namePhoto.tag = 10000 + indexPath.row;
        NSMutableArray *arr = [NSMutableArray array];
        for (NSInteger i = 1; i<= 15; i++ ) {
            NSString *count = [NSString stringWithFormat:@"q%ld",i];
            [arr addObject:count];
        }
        cell.namePhoto.image = [UIImage imageNamed:arr[indexPath.row]];
        
        return cell;
        
    }else{
        
        return nil;
    }
    
}

// 设置collectionView等屏幕
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == self.hotCollectionView) {
        
        return CGSizeMake(SCREEN_WIDTH, self.hotView.frame.size.height - 9);
        
    }else{
    
        return CGSizeMake(SCREEN_WIDTH / 3 - 15, SCREEN_HEIGHT / 4);
        
    }
}
#pragma mark collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HotBannerModel *model = self.bannerArr[indexPath.row];
    ClassifyModel *classModel = self.classifyArr[indexPath.row];

    if (collectionView == self.hotCollectionView) {
        
    NSNumber *two = [NSNumber numberWithFloat:2];
    NSNumber *three = [NSNumber numberWithFloat:3];
    
    if ([model.type isEqualToNumber:two]) {
        DetailViewController *detaVC = [[DetailViewController alloc] init];
        detaVC.idNumber = model.value;
        NSLog(@"%@",model.value);
        [self.navigationController pushViewController:detaVC animated:YES];
    }else if ([model.type isEqualToNumber:three]){
        ComiContentViewController *comicVC = [[ComiContentViewController alloc] init];
        comicVC.idNUmber = model.value;
        [self.navigationController pushViewController:comicVC animated:YES];
    }
    }else if (collectionView == self.classifyCollectionView){
        MoreComicViewController *moreVC = [[MoreComicViewController alloc] init];
        moreVC.titleData = classModel.title;
        moreVC.titleStr = classModel.title;
        [self.navigationController pushViewController:moreVC animated:YES];
    }

}

#pragma mark 定时器
- (void)addtimer{
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:4 target:self selector:@selector(scrollNext) userInfo:nil repeats:YES];
    
    // 问题:定时器不是一定准确
    // 因为 RunLoop导致 当定时器加到scrollView或者是继承于scrollview的控件上的时候,当滑动scrollView的时候,定时器会停止
    
    // 解决问题的代码
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    
    self.myTimer = timer;
}

- (NSIndexPath *)returnIndex{
    
    NSIndexPath *currentIndex = [[_hotCollectionView indexPathsForVisibleItems] lastObject];
    
    currentIndex = [NSIndexPath indexPathForItem:currentIndex.item inSection:50];
    
    [_hotCollectionView scrollToItemAtIndexPath:currentIndex atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    return currentIndex;
}

- (void)scrollNext{
    
    // 获取当前显示的indexpath
    
    NSIndexPath *currentIndex = [self returnIndex];
    
    NSInteger item = currentIndex.item + 1 ;
    
    NSInteger section = currentIndex.section;
    
    if (item == _bannerArr.count) {
        
        item = 0;
        
        section ++;
    }
    
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
    
    [_hotCollectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    
    _BannerPage.currentPage = item;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _hotCollectionView) {
    
        _BannerPage.currentPage = (NSInteger) (scrollView.contentOffset.x / SCREEN_WIDTH ) % _bannerArr.count;
    
    }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == _hotCollectionView) {

    [self removeTimer];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView == _hotCollectionView) {

    [self addtimer];
    }
}

#pragma mark 滑动时停掉计时器
- (void)removeTimer{
    
    if (_myTimer != nil) {
        
        // 停止定时器
        [self.myTimer invalidate];
        // 定时器置空
        self.myTimer = nil;
        
    }
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    if (collectionView == _hotCollectionView) {
        
        return 100;
        
    }else{
        
        return 1;
        
    }
    
}

#pragma mark TableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  self.detailsArr.count;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    HotModel *model = self.detailsArr[indexPath.row];
    
    HotTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HotTableViewCell class]) forIndexPath:indexPath];
    
    NSNumber *zero = [NSNumber numberWithFloat:0];
    
    self.type = model.type;
    
    self.titleID = model.title;
    
    if ([model.type isEqualToNumber:zero] || [model.title isEqualToString:@"所有作品"]) {
        
        cell.hotArr = model.topics;
        
    }else{
        
        cell.comicsArr = model.comics;
        
    }
    
    cell.type = model.type;
    
    cell.name = model.title;
    
    cell.moreBUtton.tag = 13000+indexPath.row;
    
    [cell.moreBUtton addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [cell.detailsCollectionView reloadData];
    
    return cell;
}


- (void)moreClick:(UIButton *)button{
    
    MoreComicViewController *moreVC = [[MoreComicViewController alloc]init];
    
    HotModel *model = self.detailsArr[button.tag - 13000];
    
    moreVC.action = model.action;
    moreVC.titleStr = model.title;
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:moreVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;

    
}

- (void)search:(UIButton *)button{
    
//    SearchViewController *searchVC = [[SearchViewController alloc] init];
//    
//    [self.navigationController pushViewController:searchVC animated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
